<template>
  <div class="app-container">
    <div class="header-actions">
      <el-button icon="el-icon-back" @click="goBack">返回</el-button>
      <h2>网站配置 - {{ websiteName }}</h2>
    </div>

    <div class="config-layout">
      <!-- 左侧：配置表单 -->
      <div class="left-panel">
        <el-card class="config-card">
          <div slot="header" class="card-header">
            <span>全局配置</span>
            <div class="header-buttons">
              <el-button
                size="small"
                icon="el-icon-document"
                @click="handleGenerateConfigFile"
              >
                生成配置文件
              </el-button>
              <el-button
                type="warning"
                size="small"
                icon="el-icon-refresh"
                @click="handleReset"
              >
                重置为默认
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-check"
                :loading="saving"
                @click="handleSave"
              >
                保存配置
              </el-button>
            </div>
          </div>

          <el-tabs v-model="activeTab" type="border-card">
            <!-- 基本信息 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form ref="basicForm" :model="form" label-width="120px">
                <el-form-item label="网站名称">
                  <el-input v-model="form.site_name" placeholder="请输入网站名称" />
                </el-form-item>
                <el-form-item label="网站描述">
                  <el-input
                    v-model="form.site_description"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入网站描述"
                  />
                </el-form-item>
                <el-form-item label="网站关键词">
                  <el-input
                    v-model="form.site_keywords"
                    placeholder="多个关键词用逗号分隔"
                  />
                </el-form-item>
                <el-form-item label="网站作者">
                  <el-input v-model="form.author" placeholder="请输入作者名称" />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- Logo 和图标 -->
            <el-tab-pane label="Logo和图标" name="logo">
              <el-form ref="logoForm" :model="form" label-width="120px">
                <el-form-item label="Logo URL">
                  <el-input v-model="form.logo_url" placeholder="https://example.com/logo.png" />
                </el-form-item>
                <el-form-item label="Favicon URL">
                  <el-input v-model="form.favicon_url" placeholder="https://example.com/favicon.ico" />
                </el-form-item>
                <el-form-item label="OG Image">
                  <el-input
                    v-model="form.og_image"
                    placeholder="社交媒体分享图片 URL"
                  />
                  <span class="form-tip">推荐尺寸: 1200x630 像素</span>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 联系信息 -->
            <el-tab-pane label="联系信息" name="contact">
              <el-form ref="contactForm" :model="form" label-width="120px">
                <el-form-item label="联系邮箱">
                  <el-input v-model="form.contact_email" placeholder="info@example.com" />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="form.contact_phone" placeholder="+1 234 567 8900" />
                </el-form-item>
                <el-form-item label="公司地址">
                  <el-input
                    v-model="form.address"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入公司地址"
                  />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 社交媒体 -->
            <el-tab-pane label="社交媒体" name="social">
              <el-form ref="socialForm" :model="form" label-width="120px">
                <el-form-item label="Facebook">
                  <el-input v-model="form.social_facebook" placeholder="https://facebook.com/yourpage" />
                </el-form-item>
                <el-form-item label="Twitter">
                  <el-input v-model="form.social_twitter" placeholder="https://twitter.com/yourhandle" />
                </el-form-item>
                <el-form-item label="LinkedIn">
                  <el-input v-model="form.social_linkedin" placeholder="https://linkedin.com/company/yourcompany" />
                </el-form-item>
                <el-form-item label="Instagram">
                  <el-input v-model="form.social_instagram" placeholder="https://instagram.com/yourhandle" />
                </el-form-item>
                <el-form-item label="YouTube">
                  <el-input v-model="form.social_youtube" placeholder="https://youtube.com/c/yourchannel" />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 菜单配置 -->
            <el-tab-pane label="菜单配置" name="menu">
              <div class="menu-config">
                <el-alert
                  title="菜单配置说明"
                  type="info"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 15px;"
                >
                  配置网站导航菜单，支持多级菜单。
                </el-alert>

                <div style="margin-bottom: 15px;">
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-plus"
                    @click="addMenuItem"
                  >
                    手动添加
                  </el-button>
                  <el-button
                    size="small"
                    icon="el-icon-document"
                    @click="showPageSelector"
                  >
                    从页面选择
                  </el-button>
                  <el-button
                    size="small"
                    icon="el-icon-refresh-left"
                    @click="autoGenerateMenu"
                  >
                    自动生成
                  </el-button>
                  <el-tooltip content="切换到右侧AI助手，让AI帮你生成菜单" placement="top">
                    <el-button
                      size="small"
                      type="text"
                      style="color: #1EB7E6;"
                    >
                      💡 提示：可通过右侧AI助手生成菜单
                    </el-button>
                  </el-tooltip>
                </div>

                <el-table
                  :data="menuItems"
                  border
                  style="width: 100%"
                  row-key="id"
                >
                  <el-table-column label="排序" width="60" align="center">
                    <template slot-scope="scope">
                      <span>{{ scope.$index + 1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" width="100">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.type === 'page'" size="mini" type="success">页面</el-tag>
                      <el-tag v-else-if="scope.row.type === 'external'" size="mini" type="warning">外链</el-tag>
                      <el-tag v-else size="mini">自定义</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="菜单名称" min-width="130">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.label" size="small" placeholder="菜单名称" />
                    </template>
                  </el-table-column>
                  <el-table-column label="链接" min-width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.url" size="small" placeholder="/about">
                        <template v-if="scope.row.page_id" slot="prepend">
                          <i class="el-icon-document" />
                        </template>
                      </el-input>
                      <div v-if="scope.row.page_name" style="font-size: 12px; color: #909399; margin-top: 2px;">
                        {{ scope.row.page_name }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="打开方式" width="120">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.target" size="small" placeholder="选择">
                        <el-option label="当前窗口" value="_self" />
                        <el-option label="新窗口" value="_blank" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-plus"
                        @click="addSubMenuItem(scope.row)"
                      >
                        子菜单
                      </el-button>
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-top"
                        :disabled="scope.$index === 0"
                        @click="moveMenuItem(scope.$index, 'up')"
                      >
                        上移
                      </el-button>
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-bottom"
                        :disabled="scope.$index === menuItems.length - 1"
                        @click="moveMenuItem(scope.$index, 'down')"
                      >
                        下移
                      </el-button>
                      <el-button
                        type="text"
                        size="small"
                        style="color: #f56c6c;"
                        icon="el-icon-delete"
                        @click="deleteMenuItem(scope.$index)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 子菜单展示 -->
                <div v-for="(item, index) in menuItems" :key="item.id" style="margin-left: 40px; margin-top: 10px;">
                  <div v-if="item.children && item.children.length > 0">
                    <div style="color: #909399; font-size: 12px; margin-bottom: 5px;">
                      「{{ item.label }}」的子菜单：
                    </div>
                    <el-table
                      :data="item.children"
                      border
                      size="small"
                      style="width: calc(100% - 40px);"
                    >
                      <el-table-column label="子菜单名称" min-width="150">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.label" size="small" placeholder="子菜单名称" />
                        </template>
                      </el-table-column>
                      <el-table-column label="链接地址" min-width="200">
                        <template slot-scope="scope">
                          <el-input v-model="scope.row.url" size="small" placeholder="/about 或 https://example.com" />
                        </template>
                      </el-table-column>
                      <el-table-column label="打开方式" width="120">
                        <template slot-scope="scope">
                          <el-select v-model="scope.row.target" size="small" placeholder="选择">
                            <el-option label="当前窗口" value="_self" />
                            <el-option label="新窗口" value="_blank" />
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="80" align="center">
                        <template slot-scope="scope">
                          <el-button
                            type="text"
                            size="small"
                            style="color: #f56c6c;"
                            icon="el-icon-delete"
                            @click="deleteSubMenuItem(index, scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- SEO 设置 -->
            <el-tab-pane label="SEO设置" name="seo">
              <el-form ref="seoForm" :model="form" label-width="150px">
                <el-form-item label="Google Analytics ID">
                  <el-input v-model="form.seo_google_analytics_id" placeholder="G-XXXXXXXXXX" />
                </el-form-item>
                <el-form-item label="Google Tag Manager">
                  <el-input v-model="form.seo_google_tag_manager" placeholder="GTM-XXXXXXX" />
                </el-form-item>
                <el-form-item label="Google Site Verification">
                  <el-input v-model="form.seo_google_site_verification" placeholder="验证代码" />
                </el-form-item>
                <el-form-item label="启用 Sitemap">
                  <el-switch v-model="form.seo_enable_sitemap" />
                </el-form-item>
                <el-form-item label="启用 Robots.txt">
                  <el-switch v-model="form.seo_enable_robots" />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- JSON 编辑器 -->
            <el-tab-pane label="JSON编辑" name="json">
              <div class="json-editor">
                <el-alert
                  title="高级配置"
                  type="warning"
                  :closable="false"
                  show-icon
                  style="margin-bottom: 15px;"
                >
                  直接编辑完整的 JSON 配置，可以添加自定义字段。请确保格式正确，否则可能导致配置损坏。
                </el-alert>
                <el-input
                  v-model="jsonConfig"
                  type="textarea"
                  :rows="20"
                  placeholder="JSON 配置"
                  @blur="handleJsonBlur"
                />
                <div class="json-actions">
                  <el-button size="small" @click="formatJson">格式化</el-button>
                  <el-button size="small" @click="validateJson">验证</el-button>
                  <el-button size="small" type="primary" @click="applyJsonToForm">应用到表单</el-button>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <!-- 右侧：AI助手 -->
      <div class="right-panel">
        <el-card class="ai-chat" shadow="never">
          <div slot="header" class="card-header">
            <span>🤖 AI配置助手</span>
            <el-button
              type="text"
              size="small"
              icon="el-icon-refresh"
              @click="resetConversation"
            >
              重新开始
            </el-button>
          </div>

          <!-- 对话历史 -->
          <div ref="chatMessages" class="chat-messages">
            <div v-if="conversationHistory.length === 0" class="welcome-message">
              <i class="el-icon-magic-stick" style="font-size: 48px; color: #1EB7E6;" />
              <h3>AI网站配置助手</h3>
              <p>我会通过几个问题帮你完善网站配置信息</p>
              <el-button
                type="primary"
                style="background-color: #1EB7E6; border-color: #1EB7E6;"
                @click="startConversation"
              >
                开始对话
              </el-button>
            </div>

            <div
              v-for="(msg, index) in conversationHistory"
              :key="index"
              :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']"
            >
              <div class="message-avatar">
                <i :class="msg.role === 'user' ? 'el-icon-user' : 'el-icon-cpu'" />
              </div>
              <div class="message-content">
                <div class="message-text">{{ msg.content }}</div>
                <div class="message-time">{{ msg.time }}</div>
              </div>
            </div>

            <!-- AI正在输入 -->
            <div v-if="aiTyping" class="message ai-message">
              <div class="message-avatar">
                <i class="el-icon-cpu" />
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span /><span /><span />
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <div class="chat-input">
            <el-input
              v-model="userInput"
              placeholder="输入你的回答..."
              :disabled="aiTyping || conversationHistory.length === 0"
              @keyup.enter.native="sendMessage"
            >
              <el-button
                slot="append"
                icon="el-icon-s-promotion"
                :loading="aiTyping"
                @click="sendMessage"
              >
                发送
              </el-button>
            </el-input>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 页面选择对话框 -->
    <el-dialog
      title="从页面选择"
      :visible.sync="pageSelectorVisible"
      width="800px"
    >
      <div style="margin-bottom: 15px;">
        <el-input
          v-model="pageSearchKeyword"
          placeholder="搜索页面名称或路径"
          prefix-icon="el-icon-search"
          clearable
          size="small"
        />
      </div>
      <el-table
        ref="pageTable"
        :data="filteredPages"
        border
        max-height="400"
        @selection-change="handlePageSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="页面名称" prop="title" min-width="150" />
        <el-table-column label="路径" prop="path" min-width="150" />
        <el-table-column label="类型" width="120">
          <template slot-scope="scope">
            {{ scope.row.page_type_display || scope.row.page_type }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_published" type="success" size="mini">已发布</el-tag>
            <el-tag v-else type="info" size="mini">草稿</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="pageSelectorVisible = false">取消</el-button>
        <el-button type="primary" @click="addPagesAsMenuItems">添加到菜单</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getWebsiteConfig,
  updateWebsiteConfig,
  resetWebsiteConfig,
  generateConfigFile
} from '@/api/static_web/config'
import { Get as getWebsite } from '@/api/static_web/website'
import { Get as getPages } from '@/api/static_web/page'

export default {
  name: 'WebsiteConfig',
  data() {
    return {
      websiteId: null,
      websiteName: '',
      websiteLanguage: 'en',
      form: {
        site_name: '',
        site_description: '',
        site_keywords: '',
        author: '',
        logo_url: '',
        favicon_url: '',
        og_image: '',
        contact_email: '',
        contact_phone: '',
        address: '',
        social_facebook: '',
        social_twitter: '',
        social_linkedin: '',
        social_instagram: '',
        social_youtube: '',
        seo_google_analytics_id: '',
        seo_google_tag_manager: '',
        seo_google_site_verification: '',
        seo_enable_sitemap: true,
        seo_enable_robots: true
      },
      activeTab: 'basic',
      saving: false,
      loaded: false,
      conversationHistory: [],
      userInput: '',
      aiTyping: false,
      jsonConfig: '',
      fullConfig: {}, // 完整配置（包含自定义字段）
      isUpdatingFromJson: false, // 防止循环更新的标志
      menuItems: [], // 菜单项
      menuIdCounter: 1, // 菜单ID计数器
      // 页面选择器
      pageSelectorVisible: false,
      websitePages: [],
      pageSearchKeyword: '',
      selectedPages: []
    }
  },
  computed: {
    filteredPages() {
      if (!this.pageSearchKeyword) {
        return this.websitePages
      }
      const keyword = this.pageSearchKeyword.toLowerCase()
      return this.websitePages.filter(page =>
        (page.title && page.title.toLowerCase().includes(keyword)) ||
        (page.path && page.path.toLowerCase().includes(keyword))
      )
    }
  },
  watch: {
    // 监听表单变化，同步更新JSON
    form: {
      handler() {
        if (!this.isUpdatingFromJson) {
          this.syncFormToJson()
        }
      },
      deep: true
    }
  },
  mounted() {
    this.websiteId = this.$route.params.id || this.$route.query.id
    if (!this.websiteId) {
      this.$message.error('缺少网站ID')
      this.goBack()
      return
    }
    this.init()
    this.loadWebsitePages()
  },
  methods: {
    // 初始化数据
    init() {
      if (this.loaded) return
      this.loaded = true

      const loading = this.$loading({
        lock: true,
        text: '加载配置中...',
        spinner: 'el-icon-loading'
      })

      getWebsite(this.websiteId).then(websiteRes => {
        this.websiteName = websiteRes.data.name
        this.websiteLanguage = websiteRes.data.language || 'en'

        return getWebsiteConfig(this.websiteId)
      }).then(configRes => {
        const config = configRes.data.global_config || {}
        const socialLinks = config.social_links || {}
        const seo = config.seo || {}

        // 保存完整配置（包含自定义字段）
        this.fullConfig = { ...config }

        this.form = {
          site_name: config.site_name || '',
          site_description: config.site_description || '',
          site_keywords: config.site_keywords || '',
          author: config.author || '',
          logo_url: config.logo_url || '',
          favicon_url: config.favicon_url || '',
          og_image: config.og_image || '',
          contact_email: config.contact_email || '',
          contact_phone: config.contact_phone || '',
          address: config.address || '',
          social_facebook: socialLinks.facebook || '',
          social_twitter: socialLinks.twitter || '',
          social_linkedin: socialLinks.linkedin || '',
          social_instagram: socialLinks.instagram || '',
          social_youtube: socialLinks.youtube || '',
          seo_google_analytics_id: seo.google_analytics_id || '',
          seo_google_tag_manager: seo.google_tag_manager || '',
          seo_google_site_verification: seo.google_site_verification || '',
          seo_enable_sitemap: seo.enable_sitemap !== undefined ? seo.enable_sitemap : true,
          seo_enable_robots: seo.enable_robots !== undefined ? seo.enable_robots : true
        }

        // 加载菜单配置
        const navigation = config.navigation || {}
        this.menuItems = navigation.items || []
        // 确保每个菜单项都有ID
        this.menuItems.forEach((item, index) => {
          if (!item.id) {
            item.id = this.menuIdCounter++
          }
          if (item.children) {
            item.children.forEach(child => {
              if (!child.id) {
                child.id = this.menuIdCounter++
              }
            })
          }
        })

        // 初始化 JSON 编辑器
        this.syncFormToJson()

        loading.close()
      }).catch(() => {
        loading.close()
        this.$message.error('加载配置失败')
      })
    },

    // 保存配置
    handleSave() {
      this.saving = true

      // 构建配置对象，包含表单字段和自定义字段
      const config = {
        ...this.fullConfig, // 保留所有自定义字段
        site_name: this.form.site_name,
        site_description: this.form.site_description,
        site_keywords: this.form.site_keywords,
        author: this.form.author,
        logo_url: this.form.logo_url,
        favicon_url: this.form.favicon_url,
        og_image: this.form.og_image,
        contact_email: this.form.contact_email,
        contact_phone: this.form.contact_phone,
        address: this.form.address,
        social_links: {
          ...(this.fullConfig.social_links || {}),
          facebook: this.form.social_facebook,
          twitter: this.form.social_twitter,
          linkedin: this.form.social_linkedin,
          instagram: this.form.social_instagram,
          youtube: this.form.social_youtube
        },
        navigation: {
          ...(this.fullConfig.navigation || {}),
          items: this.menuItems
        },
        seo: {
          ...(this.fullConfig.seo || {}),
          google_analytics_id: this.form.seo_google_analytics_id,
          google_tag_manager: this.form.seo_google_tag_manager,
          google_site_verification: this.form.seo_google_site_verification,
          enable_sitemap: this.form.seo_enable_sitemap,
          enable_robots: this.form.seo_enable_robots
        }
      }

      updateWebsiteConfig(this.websiteId, config, true).then(() => {
        this.$message.success('配置保存成功')
        this.saving = false
        // 更新完整配置
        this.fullConfig = config

        // 自动生成配置文件
        generateConfigFile(this.websiteId).then(() => {
          this.$message.success('配置文件已自动生成')
        }).catch(() => {
          // 静默失败，不影响主流程
        })
      }).catch(() => {
        this.$message.error('配置保存失败')
        this.saving = false
      })
    },

    // 生成配置文件
    handleGenerateConfigFile() {
      const loading = this.$loading({
        lock: true,
        text: '生成配置文件中...',
        spinner: 'el-icon-loading'
      })

      generateConfigFile(this.websiteId).then(response => {
        loading.close()
        this.$message.success('配置文件已生成')
        if (response.data && response.data.config_file) {
          this.$notify({
            title: '成功',
            message: `配置文件路径：${response.data.config_file}`,
            type: 'success',
            duration: 5000
          })
        }
      }).catch(() => {
        loading.close()
        this.$message.error('生成配置文件失败')
      })
    },

    // 重置配置
    handleReset() {
      this.$confirm('确定要重置为默认配置吗？这将清除所有自定义设置。', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetWebsiteConfig(this.websiteId).then(() => {
          this.$message.success('配置已重置为默认值')
          this.loaded = false
          this.init()
        }).catch(() => {
          this.$message.error('重置配置失败')
        })
      }).catch(() => {
        // 取消操作
      })
    },

    // 开始AI对话
    startConversation() {
      this.aiTyping = true
      this.callAI('')
    },

    // 发送消息
    sendMessage() {
      if (!this.userInput.trim()) {
        return
      }

      this.conversationHistory.push({
        role: 'user',
        content: this.userInput,
        time: this.getTimeString()
      })

      const userMessage = this.userInput
      this.userInput = ''
      this.aiTyping = true

      this.$nextTick(() => {
        this.scrollToBottom()
      })

      this.callAI(userMessage)
    },

    // 调用AI
    async callAI(userMessage) {
      try {
        const baseURL = process.env.VUE_APP_BASE_API || ''
        const url = baseURL + '/static_web/api/ai/website_config_assistant/'

        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': this.$store.getters.token,
            'PTOKEN': this.$store.getters.projectId
          },
          body: JSON.stringify({
            website_id: this.websiteId,
            website_language: this.websiteLanguage,
            current_config: this.form,
            user_input: userMessage,
            conversation_history: this.conversationHistory
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let aiMessage = ''
        let currentMessageIndex = null

        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          const chunk = decoder.decode(value)
          const lines = chunk.split('\n')

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6)
              if (data === '[DONE]') {
                this.aiTyping = false
                break
              }

              try {
                const parsed = JSON.parse(data)
                if (parsed.error) {
                  this.$message.error(parsed.error)
                  this.aiTyping = false
                  break
                }

                if (parsed.content) {
                  aiMessage += parsed.content

                  if (currentMessageIndex === null) {
                    this.conversationHistory.push({
                      role: 'assistant',
                      content: aiMessage,
                      time: this.getTimeString()
                    })
                    currentMessageIndex = this.conversationHistory.length - 1
                  } else {
                    this.conversationHistory[currentMessageIndex].content = aiMessage
                  }

                  // 尝试解析 JSON 配置块
                  this.extractAndApplyConfig(aiMessage)

                  this.$nextTick(() => {
                    this.scrollToBottom()
                  })
                }

                // 处理配置更新建议
                if (parsed.config_suggestion) {
                  this.applyConfigSuggestion(parsed.config_suggestion)
                }
              } catch (e) {
                // 忽略解析错误
              }
            }
          }
        }
      } catch (error) {
        this.$message.error('AI调用失败: ' + error.message)
        this.aiTyping = false
      }
    },

    // 从AI消息中提取并应用JSON配置
    extractAndApplyConfig(message) {
      // 匹配 ```json ... ``` 代码块
      const jsonMatch = message.match(/```json\s*\n([\s\S]*?)\n```/)
      if (jsonMatch) {
        try {
          const configData = JSON.parse(jsonMatch[1])

          // 如果包含导航菜单，特殊处理
          if (configData.navigation && configData.navigation.items) {
            this.applyMenuConfig(configData.navigation.items)
            // 如果只有菜单配置，不需要应用到表单
            if (Object.keys(configData).length === 1) {
              return
            }
          }

          this.applyConfigSuggestion(configData)
        } catch (e) {
          // JSON 解析失败，忽略
        }
      }
    },

    // 应用菜单配置
    applyMenuConfig(menuItems) {
      // 添加ID
      const processItems = (items) => {
        return items.map(item => ({
          ...item,
          id: this.menuIdCounter++,
          type: item.type || 'custom',
          target: item.target || '_self',
          children: item.children ? processItems(item.children) : []
        }))
      }

      this.menuItems = processItems(menuItems)
      this.$message.success('AI已生成菜单，请切换到"菜单配置"标签页查看')

      // 自动切换到菜单配置标签
      this.$nextTick(() => {
        this.activeTab = 'menu'
      })
    },

    // 应用AI的配置建议
    applyConfigSuggestion(suggestion) {
      Object.keys(suggestion).forEach(key => {
        if (key === 'social_links') {
          Object.keys(suggestion.social_links).forEach(platform => {
            const formKey = `social_${platform}`
            if (this.form[formKey] !== undefined) {
              this.form[formKey] = suggestion.social_links[platform]
            }
          })
        } else if (key === 'seo') {
          Object.keys(suggestion.seo).forEach(seoKey => {
            const formKey = `seo_${seoKey}`
            if (this.form[formKey] !== undefined) {
              this.form[formKey] = suggestion.seo[seoKey]
            }
          })
        } else if (this.form[key] !== undefined) {
          this.form[key] = suggestion[key]
        }
      })
    },

    // 重置对话
    resetConversation() {
      this.$confirm('确定要重新开始对话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.conversationHistory = []
        this.userInput = ''
        this.aiTyping = false
      }).catch(() => {
        // 取消
      })
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.chatMessages
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },

    // 获取时间字符串
    getTimeString() {
      const now = new Date()
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    },

    // 同步表单到JSON
    syncFormToJson() {
      const config = {
        ...this.fullConfig,
        site_name: this.form.site_name,
        site_description: this.form.site_description,
        site_keywords: this.form.site_keywords,
        author: this.form.author,
        logo_url: this.form.logo_url,
        favicon_url: this.form.favicon_url,
        og_image: this.form.og_image,
        contact_email: this.form.contact_email,
        contact_phone: this.form.contact_phone,
        address: this.form.address,
        social_links: {
          ...(this.fullConfig.social_links || {}),
          facebook: this.form.social_facebook,
          twitter: this.form.social_twitter,
          linkedin: this.form.social_linkedin,
          instagram: this.form.social_instagram,
          youtube: this.form.social_youtube
        },
        seo: {
          ...(this.fullConfig.seo || {}),
          google_analytics_id: this.form.seo_google_analytics_id,
          google_tag_manager: this.form.seo_google_tag_manager,
          google_site_verification: this.form.seo_google_site_verification,
          enable_sitemap: this.form.seo_enable_sitemap,
          enable_robots: this.form.seo_enable_robots
        }
      }
      this.jsonConfig = JSON.stringify(config, null, 2)
    },

    // 处理JSON手动编辑
    handleJsonBlur() {
      try {
        const parsed = JSON.parse(this.jsonConfig)
        this.fullConfig = parsed
        this.$message.success('JSON配置已更新')
      } catch (e) {
        this.$message.error('JSON格式错误，请检查语法')
      }
    },

    // 格式化JSON
    formatJson() {
      try {
        const parsed = JSON.parse(this.jsonConfig)
        this.jsonConfig = JSON.stringify(parsed, null, 2)
        this.$message.success('JSON已格式化')
      } catch (e) {
        this.$message.error('JSON格式错误，无法格式化')
      }
    },

    // 验证JSON
    validateJson() {
      try {
        JSON.parse(this.jsonConfig)
        this.$message.success('JSON格式正确')
      } catch (e) {
        this.$message.error('JSON格式错误: ' + e.message)
      }
    },

    // 添加菜单项
    addMenuItem() {
      this.menuItems.push({
        id: this.menuIdCounter++,
        label: '',
        url: '',
        target: '_self',
        children: []
      })
    },

    // 添加子菜单
    addSubMenuItem(parentItem) {
      if (!parentItem.children) {
        this.$set(parentItem, 'children', [])
      }
      parentItem.children.push({
        id: this.menuIdCounter++,
        label: '',
        url: '',
        target: '_self'
      })
    },

    // 删除菜单项
    deleteMenuItem(index) {
      this.$confirm('确定要删除该菜单项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.menuItems.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    // 删除子菜单
    deleteSubMenuItem(parentIndex, childIndex) {
      this.$confirm('确定要删除该子菜单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.menuItems[parentIndex].children.splice(childIndex, 1)
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    // 移动菜单项
    moveMenuItem(index, direction) {
      if (direction === 'up' && index > 0) {
        const temp = this.menuItems[index]
        this.$set(this.menuItems, index, this.menuItems[index - 1])
        this.$set(this.menuItems, index - 1, temp)
      } else if (direction === 'down' && index < this.menuItems.length - 1) {
        const temp = this.menuItems[index]
        this.$set(this.menuItems, index, this.menuItems[index + 1])
        this.$set(this.menuItems, index + 1, temp)
      }
    },

    // 加载网站页面列表
    loadWebsitePages() {
      // 使用查询参数方式获取页面列表
      getPages('', `website_id=${this.websiteId}&pagesize=100`).then(response => {
        // 后端返回格式: { data: { total: ..., data: [...] } }
        if (response.data && response.data.data) {
          this.websitePages = response.data.data
        } else if (Array.isArray(response.data)) {
          this.websitePages = response.data
        } else {
          this.websitePages = []
        }
        console.log('加载页面列表成功:', this.websitePages.length, '个页面')
      }).catch(error => {
        console.error('加载页面列表失败:', error)
        this.websitePages = []
        // 如果加载失败，不显示错误，静默处理
      })
    },

    // 显示页面选择器
    showPageSelector() {
      this.pageSelectorVisible = true
      this.selectedPages = []
      this.pageSearchKeyword = ''
    },

    // 处理页面选择变化
    handlePageSelectionChange(selection) {
      this.selectedPages = selection
    },

    // 将选中的页面添加为菜单项
    addPagesAsMenuItems() {
      if (this.selectedPages.length === 0) {
        this.$message.warning('请先选择页面')
        return
      }

      this.selectedPages.forEach(page => {
        this.menuItems.push({
          id: this.menuIdCounter++,
          label: page.title || page.path,
          url: page.path || `/${page.slug}`,
          target: '_self',
          type: 'page',
          page_id: page.id,
          page_name: page.title,
          children: []
        })
      })

      this.$message.success(`已添加 ${this.selectedPages.length} 个菜单项`)
      this.pageSelectorVisible = false
    },

    // 自动生成菜单（从现有页面）
    autoGenerateMenu() {
      // 检查是否有页面数据
      if (!this.websitePages || this.websitePages.length === 0) {
        this.$confirm('当前没有可用的页面，是否生成默认菜单？', '提示', {
          confirmButtonText: '生成默认菜单',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.generateDefaultMenu()
        }).catch(() => {})
        return
      }

      this.$confirm('自动生成菜单将覆盖现有菜单，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '生成菜单中...',
          spinner: 'el-icon-loading'
        })

        try {
          // 按页面类型分组
          const pagesByType = {}
          this.websitePages.forEach(page => {
            const type = page.page_type || 'other'
            if (!pagesByType[type]) {
              pagesByType[type] = []
            }
            pagesByType[type].push(page)
          })

          // 生成菜单结构
          const newMenuItems = []
          let idCounter = 1

          // 首页
          const homePages = this.websitePages.filter(p => p.is_home || p.path === '/' || p.slug === 'index')
          if (homePages.length > 0) {
            newMenuItems.push({
              id: idCounter++,
              label: '首页',
              url: '/',
              target: '_self',
              type: 'page',
              page_id: homePages[0].id,
              children: []
            })
          }

          // 其他页面类型
          const typeMap = {
            'product_catalog': '产品',
            'blog': '博客',
            'about': '关于我们',
            'contact': '联系我们'
          }

          Object.keys(typeMap).forEach(type => {
            if (pagesByType[type] && pagesByType[type].length > 0) {
              const pages = pagesByType[type]
              if (pages.length === 1) {
                newMenuItems.push({
                  id: idCounter++,
                  label: typeMap[type],
                  url: pages[0].path || `/${pages[0].slug}`,
                  target: '_self',
                  type: 'page',
                  page_id: pages[0].id,
                  children: []
                })
              } else {
              // 多个页面作为子菜单
                newMenuItems.push({
                  id: idCounter++,
                  label: typeMap[type],
                  url: pages[0].path || `/${pages[0].slug}`,
                  target: '_self',
                  type: 'page',
                  page_id: pages[0].id,
                  children: pages.slice(1).map(p => ({
                    id: idCounter++,
                    label: p.title || p.slug,
                    url: p.path || `/${p.slug}`,
                    target: '_self',
                    type: 'page',
                    page_id: p.id
                  }))
                })
              }
            }
          })

          this.menuItems = newMenuItems
          this.menuIdCounter = idCounter

          loading.close()
          this.$message.success(`已生成 ${newMenuItems.length} 个菜单项`)
        } catch (error) {
          loading.close()
          this.$message.error('生成菜单失败: ' + error.message)
          console.error('自动生成菜单错误:', error)
        }
      }).catch(() => {})
    },

    // 生成默认菜单
    generateDefaultMenu() {
      const loading = this.$loading({
        lock: true,
        text: '生成默认菜单中...',
        spinner: 'el-icon-loading'
      })

      try {
        this.menuItems = [
          {
            id: this.menuIdCounter++,
            label: '首页',
            url: '/',
            target: '_self',
            type: 'custom',
            children: []
          },
          {
            id: this.menuIdCounter++,
            label: '产品',
            url: '/products',
            target: '_self',
            type: 'custom',
            children: []
          },
          {
            id: this.menuIdCounter++,
            label: '关于我们',
            url: '/about',
            target: '_self',
            type: 'custom',
            children: []
          },
          {
            id: this.menuIdCounter++,
            label: '联系我们',
            url: '/contact',
            target: '_self',
            type: 'custom',
            children: []
          }
        ]

        loading.close()
        this.$message.success('已生成默认菜单')
      } catch (error) {
        loading.close()
        this.$message.error('生成默认菜单失败')
      }
    },

    // 应用JSON到表单
    applyJsonToForm() {
      try {
        const config = JSON.parse(this.jsonConfig)
        const socialLinks = config.social_links || {}
        const seo = config.seo || {}
        const navigation = config.navigation || {}

        this.fullConfig = config
        this.isUpdatingFromJson = true

        // 加载菜单
        this.menuItems = navigation.items || []

        this.form = {
          site_name: config.site_name || '',
          site_description: config.site_description || '',
          site_keywords: config.site_keywords || '',
          author: config.author || '',
          logo_url: config.logo_url || '',
          favicon_url: config.favicon_url || '',
          og_image: config.og_image || '',
          contact_email: config.contact_email || '',
          contact_phone: config.contact_phone || '',
          address: config.address || '',
          social_facebook: socialLinks.facebook || '',
          social_twitter: socialLinks.twitter || '',
          social_linkedin: socialLinks.linkedin || '',
          social_instagram: socialLinks.instagram || '',
          social_youtube: socialLinks.youtube || '',
          seo_google_analytics_id: seo.google_analytics_id || '',
          seo_google_tag_manager: seo.google_tag_manager || '',
          seo_google_site_verification: seo.google_site_verification || '',
          seo_enable_sitemap: seo.enable_sitemap !== undefined ? seo.enable_sitemap : true,
          seo_enable_robots: seo.enable_robots !== undefined ? seo.enable_robots : true
        }

        this.$nextTick(() => {
          this.isUpdatingFromJson = false
        })

        this.$message.success('已应用JSON配置到表单')
      } catch (e) {
        this.isUpdatingFromJson = false
        this.$message.error('JSON格式错误: ' + e.message)
      }
    },

    // 返回
    goBack() {
      this.$router.back()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin-left: 15px;
    font-size: 20px;
    font-weight: 500;
  }
}

.config-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 160px);
}

.left-panel {
  flex: 1;
  overflow-y: auto;
}

.right-panel {
  width: 400px;
  display: flex;
  flex-direction: column;
}

.config-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-buttons {
      display: flex;
      gap: 10px;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.ai-chat {
  height: 100%;
  display: flex;
  flex-direction: column;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  ::v-deep .el-card__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    overflow: hidden;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  color: #666;

  h3 {
    margin: 20px 0 10px;
    font-size: 18px;
    color: #333;
  }

  p {
    margin-bottom: 20px;
    color: #999;
  }
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s;

  &.user-message {
    flex-direction: row-reverse;

    .message-content {
      background-color: #1EB7E6;
      color: white;
    }

    .message-avatar {
      margin-left: 10px;
      background-color: #1EB7E6;
    }
  }

  &.ai-message {
    .message-avatar {
      margin-right: 10px;
      background-color: #67C23A;
    }
  }
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;

  i {
    font-size: 18px;
  }
}

.message-content {
  max-width: 70%;
  background-color: white;
  padding: 10px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-text {
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 5px;
  text-align: right;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.ai-message .message-time {
  color: #999;
}

.typing-indicator {
  display: flex;
  gap: 4px;

  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #67C23A;
    animation: typing 1.4s infinite;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  background-color: white;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.json-editor {
  ::v-deep .el-textarea__inner {
    font-family: 'Courier New', Courier, monospace;
    font-size: 13px;
    line-height: 1.5;
  }

  .json-actions {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }
}
</style>
